<?php

namespace Forwzb\Yii2Api\helper;

use yii\db\ActiveQuery;

/**
 * 数组格式转换器，封装了常用的数组转换
 */
class ArrayFormatter
{
    const CONVERT_DEFAULT = 1;
    const CONVERT_STRING = 2;
    const CONVERT_INT = 3;

    /**
     * 键值组转为属性组
     *
     * ```
     *
     * //labels：
     *  ['key1'=>'label',...]
     * //extra：
     *  ['key1'=>['field1'=>'f1','field2'=>'f2'],...]
     * //合并转换为：
     * [
     *  ['value'=>'key1','label'=>'label','field1'=>'f1','field2'=>'f2'],...
     * ]
     *
     * ```
     */
    public static function label2option($labels, $extra = [], $convert = self::CONVERT_DEFAULT): array
    {
        $options = [];
        foreach ($labels as $key => $label) {
            $options[] = [
                ...($extra[$key] ?? []),
                'value' => $convert === self::CONVERT_STRING
                    ? strval($key)
                    : ($convert === self::CONVERT_INT ? intval($key) : $key),
                'label' => $label,
            ];
        }
        return $options;
    }

    /**
     * 查询快捷转换成option
     */
    public static function query2option(ActiveQuery $query, string $labelField, string $valueField = 'id'): array
    {
        return $query->addSelect(['value' => $valueField, 'label' => $labelField])->asArray()->all();
    }
}